package com.yy.device.boot.handler;

import cn.hutool.core.util.HexUtil;
import com.yy.device.boot.protocol.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 编码器
 *
 * @author sunzhiqiang
 * @date 2022/01/26 15:46:53
 */
@Slf4j
public class ProtoEncoder extends MessageToMessageEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Message message, List<Object> out) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();
        message.encode(buffer);
        ByteBuf copy = buffer.copy();
        byte[] bytes = new byte[copy.readableBytes()];
        copy.readBytes(bytes);
        String s = HexUtil.encodeHexStr(bytes);
        log.info(s);
        out.add(buffer);
    }
}
